async function fileExistCheck(file) {

    // 文件分片计算
    const chunks = createChunks(file, 1024 * 1024); // 1MB 分片大小
    const fileId = await hash(chunks);

    // 文件校验地址路径
    let path = `https://dtools.cpolar.cn/api/dtools-utils/file/check/exist/${fileId}`

    const response = await fetch(path);
    if (response.ok) {
        // 返回文件 ID，如果为空表示文件不存在，无法走秒传逻辑
        let data = await response.json();
        console.log(data.data)
        return data.data
    }else {
        console.log("请求出错")
    }
}

async function segmentUploadFile(file, callback){
    let uploadData = {
        status: false,
        message: "初始化...",
        progress: 0,
        speed: 0,
        fileId: null,
        fileSize: (file.size / (1024 * 1024)).toFixed(1),
        fileName: file.name
    };

    if (!file) {
        uploadData.message = "请选择文件";
        callback(uploadData);
        return;
    }

    const chunks = createChunks(file, 1024 * 1024); // 1MB 分片大小
    const fileId = await hash(chunks);
    const totalSize = file.size;
    let uploadedSize = 0;
    let startTime = Date.now();
    let lastUploadedSize = 0;
    let lastUpdateTime = startTime;
    const maxConcurrentRequests = 3;
    let activeRequests = 0;
    const queue = [];

    const processQueue = () => {
        while (activeRequests < maxConcurrentRequests && queue.length > 0) {
            const { chunk, currentChunk, formData } = queue.shift();
            activeRequests++;
            requestUrl(currentChunk, chunks.length, fileId, file.name, formData)
                .then((data) => {
                    uploadedSize += chunk.size;
                    uploadData.status = false;
                    uploadData.message = "上传中...";

                    const currentTime = Date.now();
                    const timeDiff = currentTime - lastUpdateTime;
                    if (timeDiff > 0) {
                        const uploadedDiff = uploadedSize - lastUploadedSize;
                        const speed = uploadedDiff / timeDiff;
                        const speedInMB = (speed * 1000) / (1024 * 1024);

                        uploadData.progress = (uploadedSize / totalSize) * 100;
                        uploadData.speed = speedInMB.toFixed(1);
                        uploadData.fileId = data.data;
                        callback(uploadData);

                        // lastUploadedSize = uploadedSize;
                        // lastUpdateTime = currentTime;
                    }
                })
                .catch((error) => {
                    uploadData.status = false;
                    uploadData.message = `分片 ${currentChunk} 上传出错: ${error.message}`;
                    callback(uploadData);
                })
                .finally(() => {
                    activeRequests--;
                    processQueue();
                });
        }
    };

    for (let i = 0; i < chunks.length; i++) {
        const chunk = chunks[i];
        const currentChunk = i + 1;
        const formData = new FormData();
        formData.append('file', chunk);
        formData.append('fileType', "/finderIQ/test");

        queue.push({ chunk, currentChunk, formData });
    }

    processQueue();
}


async function requestUrl(currentChunk, totalChunk, fileId, fileName, formData) {
    try {
        const response = await fetch(
            `https://dtools.cpolar.cn/api/dtools-utils/file/segment/upload/${currentChunk}/${totalChunk}/${fileId}?fileName=${fileName}`,
            { method: 'POST', body: formData }
        );
        return await response.json();
    } catch (error) {
        console.log(`分片 ${currentChunk} 上传失败，正在重试...`);
        // 重试并返回新的 Promise
        return requestUrl(currentChunk, totalChunk, fileId, fileName, formData);
    }
}

function createChunks(file, chunkSize) {
    const result = [];
    for (let i = 0; i < file.size; i += chunkSize) {
        result.push(file.slice(i, i + chunkSize));
    }
    return result;
}

async function hash(chunks) {
    const chunkHashes = await Promise.all(
        chunks.map(async (chunk) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader();
                reader.onload = (e) => {
                    const arrayBuffer = e.target.result;
                    crypto.subtle.digest("SHA-256", arrayBuffer).then(
                        (hashBuffer) => {
                            resolve(hashBuffer);
                        },
                        (err) => {
                            reject(err);
                        }
                    );
                };
                reader.onerror = (err) => reject(err);
                reader.readAsArrayBuffer(chunk);
            });
        })
    );

    // 将所有分块的哈希拼接起来
    const totalHashArray = chunkHashes.reduce((acc, hashBuffer) => {
        const hashArray = new Uint8Array(hashBuffer);
        return acc.concat(Array.from(hashArray)); // 确保数字转为数组再拼接
    }, []);

    // 最终计算总哈希
    const totalHashBuffer = await crypto.subtle.digest(
        "SHA-256",
        new Uint8Array(totalHashArray)
    );

    // 将 ArrayBuffer 转换为十六进制字符串
    const hashArray = new Uint8Array(totalHashBuffer);
    return Array.from(hashArray, (byte) =>
        ("0" + byte.toString(16)).slice(-2)
    ).join("");
}

export default {
    segmentUploadFile,
    fileExistCheck
}
